package vlms.cronjob;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.TimerTask;

import vlms.bean.PremiumCustomer;
import vlms.dao.PremiumcustomerDAO;
import vlms.exception.PremiumcustomerException;

public class Subscription extends TimerTask {

	int renewalPeriodInDays = 30;
	
	public Subscription(int renewalPeriodInDays) {
		this.renewalPeriodInDays = renewalPeriodInDays;		
	}
	
	public void run() {
	
		Connection con = null;
		try {
			con = DriverManager.getConnection("jdbc:user_mysql:");
			PremiumcustomerDAO premiumcustomerDAO = new PremiumcustomerDAO();
			PremiumCustomer[] pm = premiumcustomerDAO.findAll(con);
			Calendar cal = Calendar.getInstance();
			for(int i=0;i<pm.length;i++) {
				PremiumCustomer oPM = new PremiumCustomer(pm[i]);
				Calendar cal1 = Calendar.getInstance();
				cal1.setTime(oPM.getDuedate());
				if(cal.after(cal1)) {
					cal1.add(Calendar.DATE, renewalPeriodInDays);
				}
				oPM.setDuedate(cal1.getTime());
				premiumcustomerDAO.update(oPM.getMembershipno(), oPM, con);
				con.commit();
			}
			
		}catch(SQLException e) {
			e.printStackTrace();
		} catch (PremiumcustomerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*catch(Exception e) {
			e.printStackTrace();
		}*/
		finally{
			try {
				con.close();
			} catch (SQLException e) {				
				e.printStackTrace();
			}
		}
	
	}
}
